package org.gongliang.jsmile.authc.sys.service;

import java.util.List;

import org.gongliang.jsmile.authc.sys.dao.SysDictionaryDao;
import org.gongliang.jsmile.authc.sys.entity.SysDictionary;
import org.gongliang.jsmile.common.base.CRUDService;
import org.gongliang.jsmile.common.exception.JSmileException;
import org.gongliang.jsmile.common.kit.StrKit;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
* 
* @author 龚亮
* @version 1.0
* @date 2018年08月25日 04:57:24
*/
@Service
public class SysDictionaryService extends CRUDService<SysDictionaryDao, SysDictionary> {

	/**
	 * desc:根据字典编码获取字典列表
	 */
	public List<SysDictionary> findDictByCode(SysDictionary dict) {
		return baseDao.findDictByCode(dict);
	}

	
	/**
	 * desc:批量删除资源
	 * @param ids
	 * @return
	 */
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public boolean deleteDicts(String[] ids) {
		int i=0;
		if (ids != null && ids.length >0) {
	        for(String id: ids) {
	        	if(StrKit.notBlank(id)) {
		        	i+=baseDao.deleteByPid(Integer.parseInt(id));
	        	}
	        }
		}
		i+=baseDao.deleteByIds(ids);
		return retBool(i);
	}


	public boolean saveDict(SysDictionary dictionary) {
		if(StrKit.notBlank(dictionary.getDictCode())) {
			List<SysDictionary> lists=baseDao.findDictByCode(dictionary);
			if(lists!=null&&lists.size()>0) {
				throw new JSmileException("字典编码或字典名称已经存在!");
			}
		}
		return retBool(baseDao.saveOne(dictionary));
	}

	/**
	 * desc:根据字典编码获取最大的dvalue和sort
	 */
	public SysDictionary getMaxDict(SysDictionary dictionary) {
		SysDictionary dict=baseDao.getMaxDict(dictionary);
		if(null==dict) {
			dict=new SysDictionary();
			dict.setSort(1);
			dict.setDictValue("01");
		}else {
			String value = dict.getDictValue();
			if(StrKit.notBlank(value)) {
				if(value.startsWith("0")) {
					int i = (Integer.parseInt(value.substring(1)) + 1);
					if (i == 10) {
						value = i + "";
					} else {
						value = "0" + i;
					}
				}else {
					value=(Integer.parseInt(value)+1)+"";
				}
			}
			dict.setDictValue(value);
			dict.setSort(dict.getSort()+1);
		}
		return dict;
	}

}
